import 'dart:async';

import 'package:adaptivex/adaptivex.dart';
import 'package:customer/extension/extension_widget.dart';
import 'package:customer/utils/snackbar.dart';
import 'package:customer/widgets/gyy_theme.dart';
import 'package:fluent_ui/fluent_ui.dart' as fluent;
import 'package:flutter/material.dart';

import '../../constant/db_constant.dart';
import '../../constant/edit_constant.dart';
import '../../db/entity/ProductBean.dart';
import '../../main.dart';
import '../../theme.dart';
import '../../three/datatable/datatable_header.dart';
import '../../three/datatable/responsive_datatable.dart';
import '../../widgets/gyy_dialog.dart';
import 'add_product.dart';
import 'add_product_attribute.dart';

class EditProductPage extends StatefulWidget {
  const EditProductPage({Key? key}) : super(key: key);

  @override
  _ProductListState createState() => _ProductListState();
}

class _ProductListState extends State<EditProductPage> {
  late List<DatatableHeader> _headers;

  var productDao = database.productDao; //产品
  List<ProductBean> allProduct = [];



  //每页的数量 数组
  final List<int> _perPages = [10, 20, 50, 100];

  //每页的数量 当前的
  int _currentPerPage = 10;

  //当前页
  int _currentPage = 1;

  //搜索文字
  String searchText = '';

  int _total = 100;
  //展开的一级属性
  Map<String, dynamic> expandedData = {};

  final List<Map<String, dynamic>> _sourceOriginal = [];
  List<Map<String, dynamic>> _sourceFiltered = [];
  List<Map<String, dynamic>> _sourceList = []; //
  //选中的数据：{id: 4, productName: 产品03, productCode: 03, unitPrice: 1, createTime: 2022-11-09 05:56:30.893}
  List<Map<String, dynamic>> _selectedList = [];

  String? _sortColumn;
  bool _sortAscending = true;
  bool _isLoading = true;
  late Timer delayedTimer;
  final String _searchKey1 = DbConstant.product_name;
  final String _searchKey2 = DbConstant.product_code;

  loadProduct() async {
    allProduct = await database.productDao.findAll();
    debugPrint('所有产品 == ${allProduct.length}');
    /// set data
    await _pullData();
  }

  deleteProduct(int id) async {
    await database.productDao.deleteById(id);
    await loadProduct();
  }

  //加载数据
  _pullData() async {
    setState(() => _isLoading = true);
    delayedTimer = Timer(delayedDuration, () {
      _sourceOriginal.clear();
      _sourceOriginal.addAll(_generateData());
      _sourceFiltered = _sourceOriginal;
      _total = _sourceFiltered.length;
      if (_currentPerPage > _sourceOriginal.length)
      {
        _sourceList =
            _sourceFiltered.getRange(0, _sourceOriginal.length).toList();
      }
      else
      {
        _sourceList =
            _sourceFiltered.getRange(0, _currentPerPage).toList();
      }
      setState(() => {_isLoading = false});
    });

  }

  //重置数据
  _resetData({start: 0}) async {
    setState(() => _isLoading = true);
    var _expandedLen =
        _total - start < _currentPerPage ? _total - start : _currentPerPage;
    Future.delayed(Duration(seconds: 0)).then((value) {
      _sourceList.clear();
      _sourceList =
          _sourceFiltered.getRange(start, start + _expandedLen).toList();
      setState(() => _isLoading = false);
    });
  }

  //过滤数据
  _filterData(value) {
    setState(() => _isLoading = true);
    try {
      if (value == "" || value == null) {
        _sourceFiltered = _sourceOriginal;
      } else {
        _sourceFiltered = _sourceOriginal
            .where((data) =>
        data[_searchKey1]
            .toString()
            .toLowerCase()
            .contains(value.toString().toLowerCase()) ||
            data[_searchKey2]
                .toString()
                .toLowerCase()
                .contains(value.toString().toLowerCase()))
            .toList();
      }

      _total = _sourceFiltered.length;
      var _rangeTop = _total < _currentPerPage ? _total : _currentPerPage;
      _sourceList = _sourceFiltered.getRange(0, _rangeTop).toList();
    } catch (e) {
      debugPrint(e.toString());
    }
    setState(() => _isLoading = false);
  }

  @override
  void initState() {
    super.initState();
    /// set headers
    _headers = _generateHeader();
    loadProduct(); //加载所有产品
  }

  @override
  void dispose() {
    super.dispose();
    delayedTimer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: [
          Container(
            margin: const EdgeInsets.all(10),
            constraints: const BoxConstraints(maxHeight: 800,),
            child: Card(
              child: ResponsiveDatatable(
                reponseScreenSizes: const [ScreenSize.xs],
                actions: generateActions(),
                headers: _headers,
                source: _sourceList,
                selecteds: _selectedList,
                expandedData: expandedData,
                showSelect: true,
                autoHeight: false,
                // onSort: (value) {
                //   setState(() => _isLoading = true);
                //
                //   setState(() {
                //     _sortColumn = value;
                //     _sortAscending = !_sortAscending;
                //     if (_sortAscending) {
                //       _sourceFiltered.sort((a, b) =>
                //           b["$_sortColumn"].compareTo(a["$_sortColumn"]));
                //     } else {
                //       _sourceFiltered.sort((a, b) =>
                //           a["$_sortColumn"].compareTo(b["$_sortColumn"]));
                //     }
                //     var _rangeTop = _currentPerPage! < _sourceFiltered.length
                //         ? _currentPerPage!
                //         : _sourceFiltered.length;
                //     _sourceList = _sourceFiltered.getRange(0, _rangeTop).toList();
                //     _searchKey = value;
                //
                //     _isLoading = false;
                //   });
                // },
                sortAscending: _sortAscending,
                sortColumn: _sortColumn,
                isLoading: _isLoading,
                //下拉内容
                dropContainer: (data) {
                  return AddProductAttributePage(data);
                },
                onDrop: (value, item) {
                  print("EditProductPage: $value == $item ");
                  if (value!) {
                    //记录展开数据
                    expandedData = item;
                  } else {
                    expandedData = {};
                  }
                },
                onSelect: (value, item) {
                  print("$value == $item ");
                  if (value!) {
                    if (_selectedList.isNotEmpty) {
                      _selectedList = [];
                    }
                    setState(() => {
                      _selectedList.add(item),
                    });
                  } else {
                    var index = _selectedList.indexOf(item);
                    if (index != -1) {
                      _selectedList.removeAt(index);
                    }
                    setState(() => {});
                  }
                },
                footers: [
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 15),
                    child: Text("Rows per page:"),
                  ),
                  //页数选择
                  Container(
                    child: fluent.ComboBox<int>(
                      isExpanded: false,
                      value: _currentPerPage,
                      items: _perPages.map((e) {
                        return fluent.ComboBoxItem(
                          child: Text(e.toString()),
                          value: e,
                        );
                      }).toList(),
                      onChanged: (color) {
                        setState(() => _currentPerPage = color!);
                      },
                    ),
                  ),
                  Container(
                    padding: paddingH15,
                    child: Text("$_currentPage - $_currentPerPage of $_total"),
                  ),
                  IconButton(
                    icon: backIcon,
                    onPressed: _currentPage == 1
                        ? null
                        : () {
                      _currentPage--;
                      var _nextSet = (_currentPage - 1)* _currentPerPage ;
                      if(_nextSet < _currentPerPage) _nextSet = 0;
                      setState(() {
                        _resetData(start: _nextSet);
                      });
                    },
                  ),
                  IconButton(
                    icon: forwardIcon,
                    onPressed: _total - _currentPage * _currentPerPage <= 0
                        ? null
                        : () {
                      var _nextSet = _currentPage * _currentPerPage;
                      setState(() {
                        _currentPage++;
                        _resetData(start: _nextSet);
                      });
                    },
                  )
                ],
                //头部样式
                headerDecoration: BoxDecoration(
                    color: Colors.grey[400]!,
                    border: Border(
                        bottom:
                            BorderSide(color: AppTheme.accentColor, width: 1))),
                selectedDecoration: BoxDecoration(
                  border: Border(
                      bottom:
                          BorderSide(color: AppTheme.accentColor, width: 1)),
                  color: AppTheme.accentColor,
                ),
                headerTextStyle: TextStyle(color: Colors.white),
                rowTextStyle: TextStyle(color: AppTheme.accentColor),
                selectedTextStyle: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ]));
  }

  ///构建操作栏
  generateActions() {
    return [
      sizeBoxH5,
      Expanded(
          child: fluent.TextBox(
        placeholder: 'Enter search',
        onSubmitted: (value) {
          _filterData(value);
        },
        onChanged: (value) {
          searchText = value;
        },
      )),
      TextButton(
        onPressed: () => {_filterData(searchText)},
        child: const Text("搜索").margin(const fluent.EdgeInsets.all(5)),
      ),
      sizeBoxH5,
      fluent.FilledButton(
          child: const Text(StringConstant.add),
          onPressed: () async {
            var res =
                await showWidgetDialog(context, const AddProductPage(title: StringConstant.add));
            if (DialogConstant.ok == res) {
              loadProduct();
            }
          }),
      sizeBoxH10,
      fluent.Button(
        child:  const Text(StringConstant.edit),
        onPressed: () async {
          if(_selectedList.isEmpty || _selectedList.length != 1) {
            showMessage(context, "请选择一条数据，进行编辑");
            return;
          }
          var res =
              await showWidgetDialog(context, AddProductPage(title: StringConstant.edit, id: _selectedList[0]['id']));
          fluent.debugPrint(res);
          if (DialogConstant.ok == res) {
            loadProduct();
          }
        },
      ),
      sizeBoxH10,
      fluent.FilledButton(
          //自定义按钮的颜色
          style: fluent.ButtonStyle(
              backgroundColor: fluent.ButtonState.resolveWith(
            (states) => fluent.Colors.errorPrimaryColor,
          )),
          child: Text('删除'),
          onPressed: () async {
            if(_selectedList.isEmpty || _selectedList.length != 1) {
              showMessage(context, "请选择一条数据，进行编辑");
              return;
            }
            String? res = await showContentDialog(context, '删除选中的数据？');
            fluent.debugPrint(res);
            if (DialogConstant.ok == res) {
              deleteProduct( _selectedList[0]['id']);
            }
          }),
    ];
  }


  List<Map<String, dynamic>> _generateData() {
    List<Map<String, dynamic>> temps = [];
    // ignore: unused_local_variable
    for (var data in allProduct) {
      temps.add({
        "id": data.id,
        "productName": data.productName,
        "productCode": data.productCode,
        "unitPrice": data.unitPrice,
        "allergen": data.allergen,
        "typesettingFee": data.typesettingFee,
        "printingFee": data.printingFee,
        "discount": data.discount,
        "remarks": data.remarks,
        "createTime": data.createTime
      });
    }
    return temps;
  }
}

///构建头部
_generateHeader() {
  return [
    DatatableHeader(
        text: "name", value: "productName", show: true, sortable: true),
    DatatableHeader(
        text: "code",
        value: "productCode",
        show: true,
        // flex: 2,
        sortable: true),
    DatatableHeader(
        text: "unitPrice",
        value: "unitPrice",
        show: true,
        sortable: true,
        textAlign: TextAlign.center),
    DatatableHeader(
        text: "allergen",
        value: "allergen",
        show: true,
        sortable: true,
        textAlign: TextAlign.left),
    DatatableHeader(
        text: "typeFee",
        value: "typesettingFee",
        show: true,
        sortable: true,
        textAlign: TextAlign.left),
    DatatableHeader(
        text: "printFee",
        value: "printingFee",
        show: true,
        sortable: true,
        textAlign: TextAlign.left),
    DatatableHeader(
        text: "discount",
        value: "discount",
        show: true,
        sortable: true,
        textAlign: TextAlign.left),
    DatatableHeader(
        text: "remarks",
        value: "remarks",
        show: true,
        sortable: true,
        textAlign: TextAlign.left),
    DatatableHeader(
        text: "createTime",
        value: "createTime",
        show: true,
        sortable: false,
        //自定义weight
        sourceBuilder: (value, row) {
          return Container(
            child: Text(value.toString()),
          );
        }),
  ];
}


